﻿using Furion.FriendlyException;
using Mapster;
using ZeroAdmin.Application.Entity;
using ZeroAdmin.Core;

namespace ZeroAdmin.Application;

/// <summary>
/// 角色服务
/// </summary>
public class RoleService : IRoleService
{
    /// <summary>
    /// 查询全部角色
    /// </summary>
    /// <returns></returns>
    public async Task<List<Role>> GetList()
    {
        return await SqlSugarHelper.Queryable<Role>().ToListAsync();
    }

    /// <summary>
    /// 查询角色列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageListBase<Role>> GetPageList(QueryRoleInput input)
    {
        return await SqlSugarHelper.Queryable<Role>()
            .WhereIF(!string.IsNullOrEmpty(input.RoleName), r => r.RoleName.Contains(input.RoleName))
            .WhereIF(!string.IsNullOrEmpty(input.RolePermission), r => r.RolePermission.Contains(input.RolePermission))
            .OrderByDescending(r => r.Id)
            .Select<Role>().MyToPageListAsync(input.PageIndex, input.PageSize);
    }

    /// <summary>
    /// 新增角色
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> AddRole(Role input)
    {
        if (await SqlSugarHelper.Queryable<Role>().AnyAsync(x => x.RoleName.Equals(input.RoleName)))
        {
            throw Oops.Bah("角色名称重复。");
        }
        Role role = input.Adapt<Role>();

        return await SqlSugarHelper.InsertReturnIdentityAsync(role);
    }

    /// <summary>
    /// 更新角色
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> UpdateRole(Role input)
    {
        var role = await SqlSugarHelper.Queryable<Role>().FirstAsync(x => x.Id.Equals(input.Id));
        if (role == null)
        {
            throw Oops.Bah("角色不存在。");
        }
        role = input.Adapt<Role>();
        if (await SqlSugarHelper.Queryable<Role>().AnyAsync(x => x.RoleName.Equals(input.RoleName) && x.Id != input.Id))
        {
            throw Oops.Bah("角色名称重复。");
        }

        await SqlSugarHelper.UpdateAsync(role);
        return role.Id;
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="RoleId"></param>
    /// <returns></returns>
    public async Task DeleteRole(long RoleId)
    {
        var role = await SqlSugarHelper.Queryable<Role>().FirstAsync(x => x.Id.Equals(RoleId));
        if (role == null)
        {
            throw Oops.Bah("角色不存在。");
        }
        var isExistUser = await SqlSugarHelper.Queryable<User>().AnyAsync(x => x.RoleId.Equals(role.Id));
        if (isExistUser)
        {
            throw Oops.Bah("该角色已绑定用户，无法删除。");
        }

        await SqlSugarHelper.DeleteAsync(role);
    }
}
